package com.sinovatech.ologger.actionlog.aop;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import com.sinovatech.ologger.util.LogUtil;
import com.sinovatech.ologger.util.StringHelper;

public class BeanContext implements
		ApplicationContextAware {

	private static final Log logger = LogFactory
			.getLog(BeanContext.class);

	private static BeanContext beanContext;
	
	private ApplicationContext applicationContext;

	private Map<String, Object> newCreators = new HashMap<String, Object>();

	private BeanContext() {

	}
	
	public synchronized static BeanContext getBeanContext() {
		if (beanContext == null) {
			beanContext = new BeanContext();
		}
		return beanContext;
	}

	/**
	 * 通过creator类型及beanName获取创建器
	 * 
	 * @param creator
	 * @param beanName
	 * @return
	 * @throws ClassNotFoundException
	 */
	public Object findCreatorByCreatorAndBeanName(String creator,
			String beanName) {
		Object object = null;
		if (StringHelper.isEmpty(beanName)) {
			return object;
		}
		if (StringHelper.isEmpty(creator) || creator.equals("new")) {
			object = newCreators.get(beanName);
			if (object == null) {
				try {
					Class<?> clazz = Class.forName(beanName);
					object = clazz.newInstance();
					newCreators.put(beanName, object);
				} catch (Exception e) {
					logger.error(LogUtil.stackTraceToString(e));
				}
			}
		} else if (creator.equals("spring")) {
			object = applicationContext.getBean(beanName);
		}
		return object;
	}

	public void setApplicationContext(ApplicationContext applicationContext)
			throws BeansException {
		this.applicationContext = applicationContext;
	}
}
